import React, { useState, useEffect, useRef } from 'react';
import { Button, Input, Card, Form, Row, Col, Modal, message } from 'antd';
import http from '../api/http';

const { Item } = Form;

interface CheckItem {
  id: number;
  name: string;
  mnemonicName: string;
  sex: string;
  minage: number;
  maxage: number;
  price: number;
  affiliationClassify: string;
  type: string;
  remark: string;
  attention: string;
  createtime: string;
  updatetime: string;
  ckz: string;
  status: number;
}

interface AddProps {
  visible: boolean;
  onCancel: () => void;
  currentRecord: any | null;
  onSuccess: () => void;
}

const Add: React.FC<AddProps> = ({ visible, onCancel, currentRecord, onSuccess }) => {
  const [form] = Form.useForm();
  const [checkItems, setCheckitem] = useState<CheckItem[]>([]);
  const printContainerRef = useRef<HTMLDivElement>(null);

  // 加载检查项数据
  useEffect(() => {
    if (currentRecord?.setmalId) {
      http.get<any>("Tcimpact/find", { id: currentRecord.setmalId })
        .then(res => {
          const data = Array.isArray(res.data) ? res.data : [res.data];
          setCheckitem(data);
          const initialValues: any = {};
          data.forEach(item => {
            initialValues[`result_${item.id}`] = '';
            initialValues[`ref_${item.id}`] = item.ckz || '无';
          });
          form.setFieldsValue(initialValues);
        })
        .catch(err => {
          console.error('检查项接口请求失败：', err);
          message.error('检查项加载失败，请稍后重试');
        });
    }
  }, [currentRecord, form]);

  // 完成体检提交
  const handleComplete = () => {
    form.validateFields()
      .then((values) => {
        const checkItemIdArray = checkItems.map(item => item.id);
        const resultsStringArray: string[] = checkItems.map(item => values[`result_${item.id}`] || '');

        const submitData = {
          mid: 0,
          tid: currentRecord.id,
          ids: checkItemIdArray,
          person: values.cancerExecutor,
          sds: resultsStringArray
        };

        http.post("Medical", submitData).then(res => {
          if (res.code === '1') {
            message.success('体检已完成');
            http.put("Mexam", { id: currentRecord.id, status: 1 });
            onCancel();
            onSuccess();
          }
        });
      })
      .catch(() => {
        message.error('请完善所有检查项结果和执行人信息');
      });
  };

  // 打印清单功能（修复版）
  const handlePrint = () => {
    // 1. 清除旧的打印容器
    if (printContainerRef.current) {
      document.body.removeChild(printContainerRef.current);
      printContainerRef.current = null;
    }

    // 2. 验证表单数据
    form.validateFields().then(formValues => {
      const executor = formValues.cancerExecutor || '未填写';
      const examId = currentRecord?.id || '未知';

      // 3. 创建新的打印容器
      const printDiv = document.createElement('div');
      printDiv.id = 'print-container';
      printDiv.style.position = 'absolute';
      printDiv.style.top = '-9999px';
      printDiv.style.left = '0';
      printDiv.style.width = '210mm'; // A4宽度
      printDiv.style.padding = '20mm';
      printDiv.style.boxSizing = 'border-box';
      document.body.appendChild(printDiv);
      printContainerRef.current = printDiv;

      // 4. 渲染打印内容
      printDiv.innerHTML = `
        <style>
         
          .print-content {
            font-family: "SimSun", "宋体", serif;
            font-size: 14px;
          }
          .print-header {
            text-align: center;
            margin-bottom: 20px;
          }
          .print-title {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 10px;
          }
          .print-info {
            margin-bottom: 10px;
            line-height: 1.5;
          }
          .print-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
          }
          .print-table th, .print-table td {
            border: 1px solid #000;
            padding: 8px 5px;
            text-align: center;
            word-break: break-all;
          }
          .print-table th {
            background-color: #f5f5f5;
            font-weight: bold;
          }
          .print-footer {
            margin-top: 30px;
            text-align: right;
            line-height: 1.5;
          }

          /* 打印样式隔离 */
          @media print {
            body * {
              visibility: hidden !important;
            }
            #print-container, #print-container * {
              visibility: visible !important;
              position: relative !important;
              top: 0 !important;
              left: 0 !important;
              margin: 0 !important;
              padding: 0 !important;
            }
            #print-container {
              width: 100% !important;
              height: auto !important;
              overflow: visible !important;
            }
            /* 去除页眉页脚 */
            @page {
              margin: 15mm;
              size: A4;
            }
          }
        </style>
        <div class="print-content">
          <div class="print-header">
            <div class="print-title">${currentRecord?.sname || '甲华检查（2025最新）'}体检清单</div>
            <div class="print-info">
              体检编号：${examId} | 执行人：${executor}
            </div>
            <hr style="border: 1px solid #000; margin: 10px 0;" />
          </div>

          <table class="print-table">
            <thead>
              <tr>
                <th>序号</th>
                <th>检测项目</th>
                <th>参考范围</th>
                <th>检查结果</th>
                <th>注意事项</th>
              </tr>
            </thead>
            <tbody>
              ${checkItems.map((item, index) => `
                <tr>
                  <td>${index + 1}</td>
                  <td>${item.name}</td>
                  <td>${item.ckz || '无'}</td>
                  <td>${formValues[`result_${item.id}`] || '未填写'}</td>
                  <td>${item.attention || '无'}</td>
                </tr>
              `).join('')}
            </tbody>
          </table>

          <div class="print-footer">
            <div>打印时间：${new Date().toLocaleString()}</div>
            <div>备注：本清单仅作体检记录使用</div>
          </div>
        </div>
      `;

      // 5. 确保DOM渲染完成后触发打印
      setTimeout(() => {
        window.print();
        // 打印后移除临时容器
        setTimeout(() => {
          if (printContainerRef.current) {
            document.body.removeChild(printContainerRef.current);
            printContainerRef.current = null;
          }
        }, 500);
      }, 300);

    }).catch(() => {
      message.warning('请完善表单数据后再打印');
    });
  };

  return (
    <Modal
      title="体检操作"
      open={visible}
      onCancel={onCancel}
      width={800}
      footer={null}
      maskClosable={false}
      className="exam-modal"
    >
      <Card title={currentRecord?.sname ? `[${currentRecord.sname}]` : '[甲华检查(2025最新)]'} style={{ marginBottom: '20px' }}>
        <Form form={form} layout="inline">
          {checkItems.map(item => (
            <Row key={item.id} gutter={16} style={{ marginBottom: '16px', alignItems: 'center' }}>
              <Col span={8}>
                <Item label="检测项目" style={{ marginBottom: 0 }}>
                  {item.name}
                  {item.attention && (
                    <span style={{ color: '#faad14', marginLeft: 8, fontSize: 12 }}>
                      （{item.attention}）
                    </span>
                  )}
                </Item>
              </Col>
              <Col span={8}>
                <Item
                  name={`result_${item.id}`}
                  label="结果"
                  style={{ marginBottom: 0 }}
                  rules={[{ required: true, message: `请输入${item.name}结果` }]}
                >
                  <Input placeholder={`输入${item.name}检查结果`} />
                </Item>
              </Col>
              <Col span={8}>
                <Item
                  name={`ref_${item.id}`}
                  label="参考范围"
                  style={{ marginBottom: 0 }}
                >
                  <Input disabled />
                </Item>
              </Col>
            </Row>
          ))}
          <Row gutter={16}>
            <Col span={16} offset={8}>
              <Item
                name="cancerExecutor"
                label="执行人"
                rules={[{ required: true, message: '请输入执行人姓名' }]}
              >
                <Input placeholder="执行人" />
              </Item>
            </Col>
          </Row>
        </Form>
      </Card>

      <div style={{ textAlign: 'right', marginTop: '20px' }}>
        <Button style={{ marginRight: '8px' }} onClick={onCancel}>取消</Button>
        <Button style={{ marginRight: '8px' }} onClick={handlePrint}>打印清单</Button>
        <Button type="success" onClick={handleComplete}>
          完成体检
        </Button>
      </div>
    </Modal>
  );
};

export { Add };